<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
      <el-form-item label="版本号" prop="versionCode">
        <el-input
          v-model="queryParams.versionCode"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:version:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="versionList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center"type="index" />
      <el-table-column label="客户端类型" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type==='android'">Android</span>
          <span v-else>IOS</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="versionCode" />
      <el-table-column label="下载路径" align="center" prop="downloadUrl" />
      <el-table-column label="是否强制更新" align="center" prop="isUpVersion">
        <template slot-scope="scope">
          <span v-if="scope.row.isUpVersion===1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="版本描述" align="center" prop="description" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status==='active'" style="color: #4AB7BD">启用</span>
          <span v-else style="color: #E65D6E">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==='inactive'"
            size="mini"
            type="text"
            icon="el-icon-check"
            style="color: #4AB7BD"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['system:version:changeStatus']"
          >启用
          </el-button>
          <el-button
            v-if="scope.row.status==='active'"
            size="mini"
            type="text"
            icon="el-icon-close"
            style="color: #E65D6E"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['system:version:changeStatus']"
          >禁用
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:version:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:version:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改APP版本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio-button label="android">Android</el-radio-button>
            <el-radio-button label="ios">IOS</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="APK包" prop="downloadUrl" v-if="form.type === 'android'">
          <el-upload
            style="width: 30%"
            ref="upload"
            :headers="upload.headers"
            :action="upload.url"
            accept=".apk"
            :on-success="handleAvatarSuccess"
            multiple
            :limit="1"
            name="multipartFile"
            drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="下载路径" prop="downloadUrl" v-if="form.type === 'ios'">
          <el-input v-model="form.downloadUrl" maxlength="255" placeholder="请输入下载路径"/>
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="form.versionCode" maxlength="20" placeholder="版本号规则示例：1.0.1" />
        </el-form-item>

        <el-form-item label="版本描述" prop="description">
          <el-input v-model="form.description" maxlength="255" placeholder="请输入版本描述" type="textarea" :rows="6" />
        </el-form-item>
        <el-form-item label="强制更新" prop="isUpVersion">
          <el-radio-group v-model="form.isUpVersion">
            <el-radio-button :label="0">否</el-radio-button>
            <el-radio-button :label="1">是</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
            clearable
            size="small"
            v-model="form.releaseTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" maxlength="255" type="textarea" show-word-limit placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVersion, getVersion, delVersion, addVersion, updateVersion, changeStatus } from "@/api/system/version";
import { getToken } from "@/utils/auth";
export default {
  name: "Version",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // APP版本信息表格数据
      versionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionCode: undefined,
        downloadUrl: undefined,
        description: undefined,
      },
      // 表单参数
      form: {},
      submitLoading: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadObs"
      },
      // 表单校验
      rules: {
        versionCode: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        downloadUrl: [
          { required: true, message: "APK包或者下载地址不能为空", trigger: "blur" }
        ],
        type: [
          {required: true, message: "客户端类型不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询APP版本信息列表 */
    getList() {
      this.loading = true;
      listVersion(this.queryParams).then(response => {
        this.versionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getIndex($index) {
      //表格序号
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        versionCode: null,
        downloadUrl: null,
        description: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        type: 'android',
        isUpVersion: 0,
        releaseTime: undefined,
        status: 'active',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加APP版本信息";
    },
    handleChangeStatus(row) {
      let statusText = row.status === 'active' ? '禁用' : '启用'
      let status = row.status === 'active' ? 'inactive' : 'active'
      const ids = [row.id] || this.ids;
      this.$confirm('是否确认' + statusText + '该项数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeStatus({ids: ids, status: status});
      }).then(() => {
        this.getList();
        this.msgSuccess("操作成功");
      }).catch(function () {
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVersion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改APP版本信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id != null) {
            updateVersion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.submitLoading = false;
              this.getList();
            }).catch(() => {
              this.submitLoading = false;
            });
          } else {
            addVersion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.submitLoading = false;
              this.getList();
            }).catch(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除APP版本信息编号为"' + ids + '"的数据项？').then(function() {
        return delVersion(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/version/export', {
        ...this.queryParams
      }, `version_${new Date().getTime()}.xlsx`)
    },
    handleAvatarSuccess(res, file) {
      this.form.downloadUrl = res.data.url;
    },
  }
};
</script>
